/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.item;

import bin.Item;
import bin.exc.ECadastroInvalido;
import gui.JanelaPrincipal;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Thiago
 */
public class JanelaCadastroItem extends javax.swing.JInternalFrame {

    //Atributos
    private JanelaPrincipal janelaPrincipal;
    private JButton[] arrayButtons;
    private PainelCadastroItem pnlCadastroItens;
    
    boolean novoCadastro = false;
    
    public JanelaCadastroItem(JanelaPrincipal janelaPrincipal) {
        this.janelaPrincipal = janelaPrincipal;
        initComponents();
        
        this.arrayButtons = new JButton[]{this.btNovo, this.btEditar, this.btCancelar, this.btConcluir};
        this.setDialogButtons(false);
        this.atualizarTabela();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btNovo = new javax.swing.JButton();
        btEditar = new javax.swing.JButton();
        btCancelar = new javax.swing.JButton();
        btConcluir = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        pnlItens = new javax.swing.JPanel();
        pnlScroolItens = new javax.swing.JScrollPane();
        tbItens = new javax.swing.JTable();
        jMenuBar1 = new javax.swing.JMenuBar();
        menuFechar = new javax.swing.JMenu();

        setTitle("Cadastro de Itens");
        setPreferredSize(new java.awt.Dimension(654, 464));

        btNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btNovo.png"))); // NOI18N
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });

        btEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btEditar.png"))); // NOI18N
        btEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditarActionPerformed(evt);
            }
        });

        btCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btCancelar.png"))); // NOI18N
        btCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelarActionPerformed(evt);
            }
        });

        btConcluir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/icons/btConcluir.png"))); // NOI18N
        btConcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConcluirActionPerformed(evt);
            }
        });

        tbItens.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Descrição", "Quantidade", "Preço"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.Integer.class, java.lang.Float.class
            };
            boolean[] canEdit = new boolean [] {
                false, true, true, true
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbItens.getTableHeader().setReorderingAllowed(false);
        pnlScroolItens.setViewportView(tbItens);

        javax.swing.GroupLayout pnlItensLayout = new javax.swing.GroupLayout(pnlItens);
        pnlItens.setLayout(pnlItensLayout);
        pnlItensLayout.setHorizontalGroup(
            pnlItensLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnlScroolItens)
        );
        pnlItensLayout.setVerticalGroup(
            pnlItensLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlItensLayout.createSequentialGroup()
                .addComponent(pnlScroolItens, javax.swing.GroupLayout.PREFERRED_SIZE, 321, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        menuFechar.setText("Fechar");
        menuFechar.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuFecharMouseClicked(evt);
            }
        });
        jMenuBar1.add(menuFechar);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(pnlItens, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(btNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 386, Short.MAX_VALUE)
                        .addComponent(btCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btNovo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btEditar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btConcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 4, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlItens, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //Criar painel para cadastro/edição de itens
    public void criarPainelDeCadastro(boolean novoCadastro, Item itemEdicao){
        PainelCadastroItem painelCadastroItem = new PainelCadastroItem(this.janelaPrincipal.getArmazem());
        painelCadastroItem.setSize(620,315);
        this.pnlScroolItens.setVisible(false);
        this.pnlCadastroItens = painelCadastroItem;
        this.pnlItens.add(painelCadastroItem);
        this.pnlCadastroItens.setVisible(true);
        this.repaint();
        this.revalidate();
        
        if(!novoCadastro)
        {
            this.pnlCadastroItens.editarItem(itemEdicao);
        }
        this.novoCadastro = novoCadastro;
        
        this.setDialogButtons(true);
        pnlCadastroItens.focoCompPadrao();
    }
    
    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        this.criarPainelDeCadastro(true, null);
    }//GEN-LAST:event_btNovoActionPerformed

    public void limparTabela()
    {
        DefaultTableModel dtm = (DefaultTableModel)this.tbItens.getModel();
        while(dtm.getRowCount() > 0)
        {
            dtm.removeRow(0);
        }
    }
    
    public void atualizarTabela()
    {
        DefaultTableModel dtm = (DefaultTableModel)this.tbItens.getModel();
        this.limparTabela();
        Object[] objectData = new Object[4];
        
        for(Item in : this.janelaPrincipal.getArmazem().getListaItens())
        {
            objectData[0] = in.getId();
            objectData[1] = in.getNome();
            objectData[2] = in.getQtdEstoque();
            objectData[3] = in.getPreco();
            dtm.addRow(objectData);
        }
    }
    
    private void btConcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConcluirActionPerformed

        try 
        {
            if(this.novoCadastro)
            {
                this.pnlCadastroItens.concluirCadastro();
            }
            else
            {
                this.pnlCadastroItens.concluirEdicao();
            }
            this.pnlScroolItens.setVisible(true);
            this.pnlCadastroItens.setVisible(false);
            this.tbItens.setVisible(true);
            this.setDialogButtons(false);
            this.atualizarTabela();
            this.janelaPrincipal.armazemNotify();
        } 
        catch (ECadastroInvalido ex) 
        {
            JOptionPane.showMessageDialog(this, "Nenhuma descrição informada.", "Informação", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_btConcluirActionPerformed

    private void menuFecharMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuFecharMouseClicked
        if(this.menuFechar.isEnabled())
        {
            this.janelaPrincipal.getJanelaFactory().liberarJanela("[Menu, Cadastro, Item]");
            this.dispose();
        }
    }//GEN-LAST:event_menuFecharMouseClicked

    private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed
       
        int confirm = JOptionPane.showConfirmDialog(this, "Deseja mesmo cancelar o cadastro?", "Confirmação", JOptionPane.YES_NO_OPTION);
        if(confirm == JOptionPane.YES_OPTION)
        {
            this.pnlScroolItens.setVisible(true);
            this.pnlCadastroItens.setVisible(false);
            this.tbItens.setVisible(true);
            this.setDialogButtons(false);
        }
    }//GEN-LAST:event_btCancelarActionPerformed

    private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditarActionPerformed
        if(this.tbItens.getSelectedRow() == -1)
        {
            JOptionPane.showMessageDialog(this, "Nenhum item selecionado.", "Informação", JOptionPane.INFORMATION_MESSAGE);
            return;
        }
        
        Item item = null;
        for(Item in : this.janelaPrincipal.getArmazem().getListaItens())
        {
            if((Integer)this.tbItens.getValueAt(this.tbItens.getSelectedRow(), 0) == in.getId())
            {
                item = in;
                break;
            }
        }
        this.criarPainelDeCadastro(false, item);
    }//GEN-LAST:event_btEditarActionPerformed

    //Integracao Botões
    public void setDialogButtons(boolean enable)
    {
        this.arrayButtons[0].setEnabled(!enable);
        this.arrayButtons[1].setEnabled(!enable);
        this.arrayButtons[2].setEnabled(enable);
        this.arrayButtons[3].setEnabled(enable); 
        this.menuFechar.setEnabled(!enable);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancelar;
    private javax.swing.JButton btConcluir;
    private javax.swing.JButton btEditar;
    private javax.swing.JButton btNovo;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JMenu menuFechar;
    private javax.swing.JPanel pnlItens;
    private javax.swing.JScrollPane pnlScroolItens;
    private javax.swing.JTable tbItens;
    // End of variables declaration//GEN-END:variables
}
